package com.luge.model.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.luge.base.Base;
import com.luge.heart.R;
import com.luge.model.KeyItem;
import com.luge.model.download.DownLoad.DownLoadCallBack;
import com.luge.model.download.DownLoadManager;
import com.luge.model.download.ImageManager;

public class KeyItemView extends FrameLayout implements ReleaseInterface {
	private ImageView icon;
	private TextView title;
	private Bitmap bitmap;

	public KeyItemView(Context context) {
		super(context);
		init();
	}

	public KeyItemView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		initIcon();
		initTitle();
	}

	private void initIcon() {
		icon = new ImageView(getContext());
		LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, Gravity.CENTER);
		icon.setLayoutParams(layoutParams);
		icon.setScaleType(ScaleType.CENTER_CROP);
		addView(icon);
	}

	private void initTitle() {
		title = new TextView(getContext());
		LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL);
		title.setLayoutParams(layoutParams);
		title.setBackgroundColor(getResources().getColor(
				R.color.half_transparent));
		title.setGravity(Gravity.CENTER_HORIZONTAL);
		title.setTextColor(getResources().getColor(R.color.white));
		addView(title);
	}

	public void setInfo(KeyItem item) {
		title.setText(item.getTitle());
		icon.setImageResource(R.drawable.key_item_icon);
		final String imgUrl = item.getImgUrl();
		final String filePath = ImageManager.getFilePath(Base.cache_path,
				imgUrl);
		DownLoadCallBack callBack = new DownLoadCallBack() {

			@Override
			public void success(String urlPath) {
				try {
					if (imgUrl.equals(urlPath)) {
						bitmap = BitmapFactory.decodeFile(filePath);
						icon.setImageBitmap(bitmap);
					}
				} catch (OutOfMemoryError e) {

				}
			}

			@Override
			public void progress(int progress) {

			}

			@Override
			public void fail() {
				icon.setImageResource(R.drawable.key_item_icon);
			}
		};
		DownLoadManager.getInstance().add(imgUrl, filePath, callBack);
	}

	@Override
	public void release() {
		if (bitmap != null) {
			bitmap.recycle();
		}
	}
}
